<template>
  <div class="svg-content" :id="id">
    <svg width="0" height="0">
      <defs>
        <filter :id="id + '_filter'">
          <feOffset result="offOut" in="SourceGraphic" dx="0" dy="0"/>
          <feGaussianBlur result="blurOut" in="offOut" stdDeviation="2"/>
          <feBlend in="SourceGraphic" in2="blurOut" mode="normal"/>
        </filter>
      </defs>
    </svg>
  </div>
</template>
<script>
    import {d3, svgInit} from "./svgs";

    export default {
        props: {
            data: {
                type: Array,
                default: () => []
            },
            defaultIndex: Number,
            id: String,
        },
        data() {
            return {
                width: 290,
                height: 290,

                offsetStartAngle: 0,
                mask: false,
                lineWidth: 15, // 进度条宽
                offset: 20,
                diameter1: 260, //
                diameter2: 180, //
                innerRadius: 27, // 圆形进度条中心线的半径
                padding: 6,//
                circleBackground: "rgba(0,123,255,0.2)",
                stroke: "#00FFF3",
                titleFontSize: 60,
                nameFontSize: 22,
                strokeWidth: 1, // 进度条边框宽度
                startAngle: -Math.PI // 起始角度，0为3点钟方向
            };
        },
        mounted() {
            svgInit(this.drawSvg, this.id, [this.width, this.height, this.diameter1, this.diameter2, this.titleFontSize, this.nameFontSize, this.offset]);
        },
        methods: {
            drawSvg(svg, id, width, height, diameter1, diameter2, titleFontSize, nameFontSize, offset) {
                let me = this;
                const oriData = [];
                this.data.forEach(item => {
                    let obj = {};
                    obj.y = item.conut;
                    obj.x = item.UnitName;
                    oriData.push(obj);
                });

                svg.attr("width", width)
                    .attr("height", height);

                //绘制中间文字
                let g = svg.append("g")
                    .attr("transform", `translate( ${width / 2}, ${height / 2-5} )`);

                // 计算偏移值

                let item = Math.PI * 2 / oriData.length;
                let centerItemEndAngle = item * Math.ceil(oriData.length / 2);
                let centerItemStartAngle = item * Math.floor(oriData.length / 2);
                let centerOffset;
                if (oriData.length % 2 === 1) {
                    centerOffset = (centerItemEndAngle + centerItemStartAngle) / 2 - Math.PI;
                }
                else {
                    centerOffset = (centerItemEndAngle + centerItemStartAngle) / 2 - Math.PI + item / 2;
                }
                //生成饼图数据
                let arc = d3.arc()
                // .outerRadius(radius)
                    .cornerRadius(0);
                let drawData = d3
                    .pie()
                    .value(40)
                    .sort(null)
                    .sortValues(null)
                    .startAngle(-centerOffset)
                    .endAngle(Math.PI * 2 - centerOffset)
                    .padAngle(0.02)(oriData);

                //生成色值序列
                let colorScale = d3
                    .scaleOrdinal()
                    .domain(d3.range(0, oriData.length))
                    .range(["#D0E3FF", "#BED8FF", "#9BC3FF", "#75ACFF", "#4A93FF", "#2E82FF", "#1372FF", "#1765FC", "#0B59F1", "#054DD9", "#0046CD", "#0043C4"]);

                let circle = g.append("g")
                    .attr("id", "circleGroup")
                    .attr("stroke", "steelblue")
                    .attr("stroke-width", 1)
                    .selectAll("path")
                    .data(drawData)
                    .enter()
                    .append("path")
                    .attr("id", (d, i) => `${me.id}_path_${i}`)
                    .attr("style", "cursor: pointer")
                    .attr("fill", function (d) {
                        return colorScale(d.index);
                    })
                    .attr("d", function (d, i) {
                        if (i === me.defaultIndex) {
                            d.outerRadius = diameter1 / 2 + offset;
                            d.innerRadius = diameter2 / 2 - offset;
                            me.offsetStartAngle = d.startAngle;
                        }
                        else {
                            d.outerRadius = diameter1 / 2;
                            d.innerRadius = diameter2 / 2;

                        }
                        return arc(d);
                    })
                    .on("click", arcClick(150));

				let text0 = g.append("text")
					.text(oriData[me.defaultIndex].y)
					.attr("style", `font-size:${titleFontSize}px;font-family:BebasNeue;fill:white;text-anchor: middle;dominant-baseline: middle`)
					.attr("transform", `translate(0,-${offset * 1.5})`);
				let text1 = g.append("text")
					.text(oriData[me.defaultIndex].x)
					.attr("style", `font-size:${nameFontSize}px;font-family:PingFang;fill:white;text-anchor: middle;dominant-baseline: middle,font-weight:400`)
					.attr("transform", `translate(0,${offset * 1.5})`);



				// 初始动画效果
                circle.transition()
                    .duration(2000)
                    .attrTween("d", function (d) {
                        //初始加载时的过渡效果
                        let fn = d3.interpolate({
                            endAngle: d.startAngle
                        }, d);
                        return function (t) {
                            return arc(fn(t));
                        };
                    })
                    // .on("end", (d, i) => {
                    //     //不用if的话会触发多次
                    //     if (i === 0) {
                    //         let clickEvent = new Event("click");
                    //         document.querySelector(`#${me.id}_path_${me.defaultIndex}`).dispatchEvent(clickEvent);
                    //     }
                    // });


                function arcClick(delay) {
                    // 设置缓动函数,为鼠标事件使用
                    me.mask = true;
                    return (d, index) => {
                        me.$emit("offset-click", index);
                        text0.text(oriData[index].y);
                        text1.text(oriData[index].x);
                        let offsetAngle = me.offsetStartAngle - d.startAngle;
                        circle
                            .transition()
                            .delay(delay)
                            .attrTween("d", (d2, j) => {
                                let obj = JSON.parse(JSON.stringify(d2));
                                d2.startAngle = d2.startAngle + offsetAngle;
                                d2.endAngle = d2.endAngle + offsetAngle;
                                if (index === j) {
                                    if (d2.outerRadius < diameter1 / 2 + offset) {
                                        d2.outerRadius = d2.outerRadius + offset;
                                        d2.innerRadius = diameter2 / 2 - offset;
                                    }
                                }
                                else {
                                    d2.outerRadius = diameter1 / 2;
                                    d2.innerRadius = diameter2 / 2;
                                }
                                let i = d3.interpolate({
                                    startAngle: obj.startAngle,
                                    endAngle: obj.endAngle,
                                    outerRadius: obj.outerRadius
                                }, d2);
                                return (t) => {
                                    return arc(i(t));
                                };
                            })
                            .on("end", () => {
                                me.mask = false;
                            });
                    };
                }


            }
        }
    };
</script>
